<script lang="ts" setup>
import * as Yup from 'yup'
/**
 * query参数，i：id，e：email，name，ty
 */

defineOptions({
  name: 'LoginThird',
})
definePageMeta({
  layout: 'other',
})

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()

const schema = Yup.object().shape({
  username: Yup.string(),
  email: Yup.string(),
  password: Yup.string(),
})
const { bool: isEmailEmptyAndMust } = useBoolean(false)

const paramsString = window.location.search
const searchParams = new URLSearchParams(paramsString)
const username = ref('')
const userExist = ref('')
const email = ref(searchParams.get('e') || '')
const emailExist = ref('')
const password = ref('')
const curExists = ref<1 | 2 | 3>(2)
const curParams = ref()
const id = ref(searchParams.get('i') || '')
const ty = ref(searchParams.get('ty') || '')
const psdColor = ref('#FC3C3C')

const { runAsync: runExists } = useRequest(ApiMemberExists, {
  onSuccess() {
    if (curExists.value == 1) {
      userExist.value = ''
    }
    if (curExists.value == 2) {
      emailExist.value = ''
    }
  },
  onError: () => {
    if (curExists.value === 1) {
      userExist.value = $t('choose_another_name')
      message.error($t('choose_another_name'))
    }
    if (curExists.value === 2) {
      emailExist.value = $t('email_exists')
      message.error($t('email_exists'))
    }
  },
})
const { run: runThirdReg } = useRequest(ApiMemberThirdReg, {
  onSuccess: async (data) => {
    appStore.setToken(data)
    Session.remove(STORAGE_THIRDREG_PARAMS_KEYWORDS)
    message.success(`${$t('tip_pop_up_reg_success_title')} ${curParams.value?.username}!`)
    await nextTick()

    setTimeout(() => {
      i18nNavigateTo('/')
    }, 100)
  },
})

function goLogin() {
  i18nNavigateTo('/login/signin')
}

function validEmail(value: string) {
  if (!emailReg.test(value))
    return $t('email_address_incorrect')
  else if (value && value.length > 30)
    return $t('pls_input_email')
  return ''
}
function onPsdBlur() {
  const res = validPsd(password.value)
  if (res) {
    message.error(res)
  }
}

function validUser(value: string) {
  if (value.length < 6)
    return $t('min_len_char', { delta: 6 })
  else if (value.match('[^a-zA-Z0-9]'))
    return $t('name_has_invalid_char')
  else if (value.length > 30)
    return $t('max_len_char', { delta: 30 })
  else if (!usernameReg.test(value))
    return $t('validate_msg_user_name_tip')
  return ''
}
function validPsd(value: string) {
  if (value.length < 8)
    return $t('pop_up_create_account_password_least_8_characters')
  else if (!upperLowerReg.test(value))
    return $t('pop_up_create_account_password_uppercase_lowercase_letter')
  else if (!lastOneNumberReg.test(value))
    return $t('pop_up_create_account_password_least_1_number')
  return ''
}

function onBack() {
  router.back()
}
async function onSubmit(values: any) {
  if (userExist.value || emailExist.value) {
    message.error(userExist.value || emailExist.value)
    return
  }
  const userErr = validUser(values.username)
  let emailErr
  if (isEmailEmptyAndMust.value) {
    emailErr = validEmail(values.email)
  }
  const psdErr = validPsd(values.password)

  if (userErr || emailErr || psdErr) {
    message.error(userErr || emailErr || psdErr)
    return
  }

  const thirdReg: IMemberThirdReg = {
    email: email.value,
    username: username.value,
    third_id: id.value,
    third_type: Number(ty.value),
    device_number: await application.getDeviceNumber(),
    parent_uid: route.query.u?.toString() || (Local.get(STORAGE_UUUUU)?.value || '') as string,
    password: password.value,
    c: route.query.c?.toString() || (Local.get(STORAGE_CCCCC)?.value || '') as string,
    // phone: phoneField.value,
  }

  curParams.value = thirdReg
  // 把第三方注册信息存储到session中，就把正常注册信息删除
  Session.set(STORAGE_THIRDREG_PARAMS_KEYWORDS, thirdReg)
  Session.remove(STORAGE_REG_PARAMS_KEYWORDS)
  runThirdReg(curParams.value)
}
async function onEmailUsernameBlur(type: 1 | 2 | 3) {
  const usernameErr = validUser(username.value)
  const emailErr = validEmail(email.value)
  if (usernameErr || emailErr) {
    message.error(usernameErr || emailErr)
    return
  }
  curExists.value = type
  if (type === 1 && username.value && !usernameErr)
    await runExists({ ty: type, val: username.value, noNotify: true })
  if (type === 2 && email.value && !emailErr)
    await runExists({ ty: type, val: email.value })
}

function changeBorder(a: string) {
  psdColor.value = a
}
</script>

<template>
  <div class="h-full">
    <div class="size-full bg-[#232626]">
      <div class="relative w-full">
        <BaseImage url="/images/webp/header/h5-header.png" class="w-full aspect-[414/237]" />
        <div class="absolute top-0 w-full flex justify-between items-center px-6 py-3">
          <div>logo</div>
          <BaseButton class="w-8 !h-8 bg-[rgba(255,255,255,.05)] rounded" type="none" @click="onBack">
            <BaseIcon name="uni-close" class="text-xl" />
          </BaseButton>
        </div>
      </div>

      <div class="py-5 px-6 relative w-full">
        <div class="w-full mb-3">
          <div class="text-base font-semibold mb-1.5">
            {{ $t('regist') }} OAuth
          </div>
          <div class="text-[#A8AEB0] text-xs font-extrabold">
            {{ $t('pls_type_your_more_info') }}
          </div>
        </div>
        <div class="mb-3">
          <BaseForm :schema="schema" autocomplete="off" @submit="onSubmit">
            <BaseInput
              name="username"
              required
              class="mb-3"
              :placeholder="$t('username_need', [6, 18])"
              :model-value="username"
              @update:model-value="(v) => username = v"
              @blur="onEmailUsernameBlur(1)"
            />
            <BaseInput
              name="email"
              required
              class="mb-3"
              :placeholder="$t('email')"
              :model-value="email"
              @update:model-value="(v) => email = v"
              @blur="onEmailUsernameBlur(2)"
            />
            <BaseInput
              name="password"
              required
              class="mb-3"
              :style="{ '--bc-input-focus-border-color': psdColor }"
              type="password"
              :model-value="password"
              :placeholder="$t('password')"
              @update:model-value="(v) => password = v"
              @blur="onPsdBlur"
            />
            <BasePsdColor v-if="password" :password="password" class="mb-3" @border-color="changeBorder" />
            <BaseButton type="primary" html-type="submit" class="w-full text-xs h-10">
              {{ $t('start_game') }}
            </BaseButton>
          </BaseForm>

          <div class="center mt-4 font-extrabold text-[#B3BEC1]" @click="goLogin">
            <BaseIcon name="uni-arrow-down" class="text-base mr-.5 rotate-90" />{{ $t('return_login') }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
